<?php
/*
 * Copyright 2009 Chen Ze <http://chenze.name/>
 *
 *
 * @License BSD 
 *
 */

class Remoter {
    const OS_MAC=1;
    const OS_LINUX=2;
    const OS_WIN=3;
    const OS_UNKNOWN=4;

    const UA_FIREFOX=1; 
    const UA_SAFARI=2;
    const UA_IE=3;
    const UA_CHROME=4;
    const UA_OPERA=5;
    const UA_UNKNOWN=6;

    public function os() {
        $ua=$_SERVER['HTTP_USER_AGENT'];
        if (stripos($ua, 'Windows')!==false) {
            $os=self::OS_WIN;
        } else if (stripos($ua, 'Macintosh')!==false) {
            $os=self::OS_MAC;
        } else if (stripos($ua, 'Linux')!==false) {
            $os=self::OS_LINUX;
        } else {
            $os=self::OS_UNKNOWN;
        }
        return $os;
    } 
    public function ua() {
        $ua=$_SERVER['HTTP_USER_AGENT'];
        if (stripos($ua, 'MSIE')!==false) {
            $ua2=self::UA_IE;
        } else if (stripos($ua, 'Firefox')!==false) {
            $ua2=self::UA_FIREFOX;
        } else if (stripos($ua, 'chrome')!==false) {
            $ua2=self::UA_CHROME;
        } else if (stripos($ua, 'safari')!==false) {
            $ua2=self::UA_SAFARI;
        } else if (stripos($ua, 'opera')!==false) {
            $ua2=self::UA_OPERA;
        } else{
            $ua2=self::UA_UNKNOWN;
        }
        return $ua2;
    }
    public function lang() {
    }
    /*
       is_frontend 是否处于前端直接被客户访问
       例如前端有HTTP反向代理，则应该设为false
       注意，ip dr或者ip隧道模式的情况下，
       虽然服务器不直接面对客户的请求，还是应该设为true

    　加入这个是因为在不存在HTTP反向代理或者类似的情况下，HTTP_*是很容易被客户构造出来的，因为PHP会把http头里的数据都保存为HTTP_key=value。例如curl --header "X_FORWARDED_FOR"，会产生HTTP_X_FORWARDED_FOR变量。这样就给客户端欺骗带来了可能。
    */
    public function ip($is_frontend=true) {
        if ($is_frontend) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        }
        if (strpos($ip, ",")) {
            $ips = explode(",", $ip);
            return trim($ips[0]);
        }
        return $ip;
    }
}
